var selectApprover = false;//此参数 验证是否选择了审批人
var piseCase = null; // 根据此参数 验证必填项

// 编辑页默认显示几个审批人
function editShowAudit ( amount ) {
    if (amount < 100000) {
        for ( var i = 0; i <= 2; i++ ) {
            $(".approver").eq(i).css("display","block");
        }
        piseCase = 1;
    } else if ( amount >= 100000 && amount <= 500000 ) {
        for ( var i = 0; i <= 3; i++ ) {
            $(".approver").eq(i).css("display","block");
        }
        piseCase = 2;
    } else {
        for ( var i = 0; i <= 4; i++ ) {
            $(".approver").eq(i).css("display","block");
        }
        piseCase = 3;
    }
    if ($(".copy")) {
        $(".copy").css("display","block");
    }
}

//点击分类
var unlock = true;
$(document).on("click",".level1",function(){
    if (unlock == false) {
        return;
    }
    unlock = false;
    $("#searchValue").val("");
    var sib1 = $(this).siblings(".level2-box");
    var category = $(this).children().data("category");
    sib1.slideToggle(function(){
        unlock = true;
    });
    if(!$(this).children().find(".am-icon-angle-right").hasClass("transform90")){
        $(this).children().find(".am-icon-angle-right").addClass("transform90");
    }else{
        $(this).children().find(".am-icon-angle-right").removeClass("transform90");
    }
    levelClick(category,1,1);
});
$(document).on("click",".level2",function(){
    if (unlock == false) {
        return;
    }
    unlock = false;
    $("#searchValue").val("");
    var sib2 = $(this).siblings(".level3-box");
    var category = $(this).children().data("id");
    sib2.slideToggle(function(){
        unlock = true;
    });
    if(!$(this).children().find(".am-icon-angle-right").hasClass("transform90")){
        $(this).children().find(".am-icon-angle-right").addClass("transform90");
    }else{
        $(this).children().find(".am-icon-angle-right").removeClass("transform90");
    }
    levelClick(category,2,1);
});
$(document).on("click",".level3",function(){
    $("#searchValue").val("");
    var category = $(this).children().data("id");
    levelClick(category,3,1);
});

// 点击选择审批人
$( document ).on( "click", "#sure", function () {
    if ( $(this).text() == '选择审批人' ) {
        selectApprover = true;
        var priceA = parseFloat(getAllPrice());

        if (priceA == 0) {
            $("#pop-up-content").text("请选择商品");
            $("#my-alert").modal();
            return false;
        }

        $(".quantity").map(function () {
            $(this).attr("readonly", "readonly");
        });
        $(".price").map(function () {
            $(this).attr("readonly", "readonly");
        });
        $(".remarks").map(function () {
            $(this).attr("readonly", "readonly");
        });
        $(".specification-btn").map(function () {
            $(this).prop("disabled",true);
        });
        $("#chooseCommodity").prop("disabled",true);
        $(".delect-btn").prop("disabled",true);
        $(this).text('重选商品');
        $(".my-hint").text("请选择审批人");

        if (priceA < 100000) {
            for ( var i = 0; i <= 2; i++ ) {
                $(".approver").eq(i).css("display","block");
            }
            piseCase = 1;
        } else if ( priceA >= 100000 && priceA <= 500000 ) {
            for ( var i = 0; i <= 3; i++ ) {
                $(".approver").eq(i).css("display","block");
            }
            piseCase = 2;
        } else {
            for ( var i = 0; i <= 4; i++ ) {
                $(".approver").eq(i).css("display","block");
            }
            piseCase = 3;
        }
        if ($(".copy")) {
            $(".copy").css("display","block");
        }
        
    } else if ($(this).text() == '重选商品') {
        selectApprover = false;
        $("#manager").val("");
        $("#safeguard").val("");
        $("#deputy").val("");
        $("#fdeputy").val("");
        $("#chaireman").val("");
        if ($("#financial")) {
            $("#financial").val("");
        }
        $(".quantity").map(function () {
            $(this).attr("readonly", false);
        });
        $(".price").map(function () {
            $(this).attr("readonly", false);
        });
        $(".remarks").map(function () {
            $(this).attr("readonly", false);
        });
        $(".specification-btn").map(function () {
            $(this).prop("disabled",false);
        });
        $("#chooseCommodity").prop("disabled",false);
        $(".delect-btn").prop("disabled",false);
        $(this).text('选择审批人');
        $(".my-hint").text("编辑完商品后点击下方按钮添加审批人");
        for ( var i = 0; i <= 4; i++ ) {
            $(".approver").eq(i).css("display","none");
        }
        if ($(".copy")) {
            $(".copy").css("display","none");
        }
        $("select").trigger('changed.selected.amui');
    }
});

// 添加是否删除confirm模态框
(function() {
    var html = '';
    html += '<div class="am-modal am-modal-confirm" tabindex="-1" id="my-confirm">';
    html += '  <div class="am-modal-dialog">';
    html += '    <div class="am-modal-hd">提示</div>';
    html += '    <div class="am-modal-bd">你，确定要删除这条记录吗？</div>';
    html += '    <div class="am-modal-footer">';
    html += '      <span class="am-modal-btn" data-am-modal-cancel>取消</span>';
    html += '      <span class="am-modal-btn" data-am-modal-confirm>确定</span>';
    html += '    </div>';
    html += '  </div>';
    html += '</div>';
    $("body").append(html); 
})();
// 点击删除按钮删除相应商品
$(document).on("click", ".delect-btn", function () {
    $(this).parents("tr.line").addClass("js-do-del");   
    $('#my-confirm').modal({
        onConfirm: function() {
            $("tr.line.js-do-del").remove();
        },
        onCancel: function() {
            $("tr.line.js-do-del").removeClass("js-do-del");
        }
    });
});

// 计算商品总数量，价格。
function calcPriceAndNum(){
    var quantityOne;
    var goodsPrice;
    var priceOne;
    var quantity = 0;  //所有商品数量
    $(".quantity").bind("input propertychange",function(){
        var tr = $(this).parents(".line");
        quantityOne = $(this).val() == "" ? 0 : parseFloat($(this).val());
        priceOne = tr.find(".price").val();
        priceOne = priceOne == "" ? 0 : parseFloat(priceOne);

        goodsPrice = (quantityOne * priceOne).toFixed(2);
        tr.find(".price-all").text(goodsPrice);
        var quantityLen = $(".line").find(".quantity").length;
        for(var i = 0;i < quantityLen;i++){
            var num = $(".line").find(".quantity").eq(i).val();
            num = parseInt(num == "" ? 0 : num);
            quantity += num;
        }
        $("#quantity-all").text(quantity);
        quantity = 0;

        var allPrice = getAllPrice();
        $("#all-money").val(allPrice);
        var amountBig = digitUppercase(allPrice);
        $("#amountBig").val(amountBig);
    });
    $(".price").bind("input propertychange",function(){
        var tr = $(this).parents(".line");
        priceOne = $(this).val() == "" ? 0 : parseFloat($(this).val());
        quantityOne = tr.find(".quantity").val();
        quantityOne = quantityOne == "" ? 0 : parseFloat(quantityOne);
        goodsPrice = (quantityOne * priceOne).toFixed(2);
        tr.find(".price-all").text(goodsPrice);


        var allPrice = getAllPrice();
        $("#all-money").val(allPrice);
        var amountBig = digitUppercase(allPrice);
        $("#amountBig").val(amountBig);
    });
}

//返回总价
function getAllPrice(){
    var priceLen = $("#goodsMessage").find(".price-all").length;
    var amount = 0;
    for(var i = 0;i < priceLen; i++){
        var one = $("#goodsMessage").find(".price-all").eq(i).text();

        one = one == "" ? 0 : parseFloat(one);
        amount += parseFloat(one);
    }

    amount = amount.toFixed(2);
    return amount;  
}

//获取商品详情信息
function getGoodsMessage(){
    var goods = [];
    var goodsBox = $("#goodsMessage").find(".line");
    if($("#documentTime").length) {
        var createTime = $("#documentTime").val();
    }
    for(var i = 0;i < goodsBox.length; i++){
        var good = {};
        var oneGoods = goodsBox.eq(i);
        var order = oneGoods.find(".order").text();
        var dataId = oneGoods.find(".product_no").data("id");
        var ckId = oneGoods.find(".product_no").data("ckid");
        var product_no = oneGoods.find(".product_no").text();
        var name = oneGoods.find(".name").text();
        var specification = oneGoods.find(".specification").html();
        var stockPriceId = oneGoods.find(".specification").data("id") ? oneGoods.find(".specification").data("id") : '';
        var goodsUnit = oneGoods.find(".goodsUnit").text();
        var quantity = oneGoods.find(".quantity").length ? oneGoods.find(".quantity").val() : '';
        var price = oneGoods.find(".price").length ? oneGoods.find(".price").val() : '';
        var priceAll = oneGoods.find(".price-all").text();
        var remarks = oneGoods.find(".remarks").length ? oneGoods.find(".remarks").val() : '';
        if($("#documentTime").length) {
            good.createTime = createTime;
        }
        good.order = order;
        good.dataId = dataId;
        good.ckId = ckId;
        good.product_no = product_no;
        good.name = name;
        good.specification = specification;
        good.stockPriceId = stockPriceId;
        good.goodsUnit = goodsUnit;
        good.quantity = quantity;
        good.price = price;
        good.priceAll = priceAll;
        good.remarks = remarks;
        goods[i] = good;
    }
    var goodsMessageJson = JSON.stringify(goods);
    return goodsMessageJson;
}

//初始化商品分类
function initCategory(){
    var divCategory = $(".left-list");
    divCategory.empty();
    $.ajax({
        url:"/api/goods/categoryData",
        data:"",
        dataType:"json",
        type:"post",
        beforeSend: function () {
            var loading = '<img src="/assets/img/loading.gif" style="width: 80px;position: absolute;left: 50%;bottom: 50%;margin-left: -40px;margin-bottom: -40px;" />'
            $(".left-list").append(loading);
            $(".list-title").css("display","none");
        },
        success:function(data){
            for(var i =0; i<data.length; i++){
                var text="";
                var ul="";
                ul ='<ul class="level1-content">'+
                '<li class="level1">'+
                '<a href="javascript:;" data-category="'+ data[i].category +'" data-type="1">'+ 
                ''+data[i].name+'<span class="am-icon-angle-right sidebar-nav-link-logo"></span></a></li>'+
                '<li class="level2-box">';

                if(data[i].two.length == 0){
                    text += '<ul class="level2-content">'+
                                '<li class="level2"></li>'+
                                '<li class="level3-box">'+
                                    '<ul class="level3-content">'+
                                        '<li></li>'+
                                    '</ul>'+
                                '</li>'+
                            '</ul>';
                }else{
                    for(var j = 0;j < data[i].two.length; j++){
                        text += '<ul class="level2-content">'+
                                    '<li class="level2"><a href="javascript:;" data-type="2" data-category="'+ data[i].two[j].one_category +'" data-id="'+ data[i].two[j].id +'"><span class="am-icon-angle-right sidebar-nav-link-logo"></span>'+data[i].two[j].name+'</a></li>'+
                                    '<li class="level3-box">'+
                                    '<ul class="level3-content">';

                        if(data[i].two[j].three.length == 0){
                            text += '<li></li>';
                        }else{
                            for(var k = 0;k < data[i].two[j].three.length; k++){
                                text += '<li class="level3">'+
                                            '<a href="javascript:;" data-type="3" data-id="'+ data[i].two[j].three[k].id +'" data-parentid="'+ data[i].two[j].id +'" data-level="2" >'+ data[i].two[j].three[k].name +
                                        '</a></li>';
                            }
                        }
                        
                        text +='</ul></li></ul>';
                    }
                }
                text +='</li></ul><hr>';
                ul += text;
                divCategory.append(ul);
            }
        },
        complete: function () {
            $(".left-list img").remove();
            $(".list-title").css("display","block");
        }
    });
}

//请求相应商品
function levelClick(category,type,page,search){
    var search = arguments[3] ? arguments[3] : null;
    $.ajax({
        url:"/api/goods/goodsByCategory",
        data:{
            category: category,
            type: type,
            page: page,
            search: search
        },
        dataType:"json",
        type:"post",
        beforeSend: function () {
            var loading = '<img src="/assets/img/loading.gif" style="width: 60px;position: absolute;left: 50%;bottom: 50%;margin-left: -30px;margin-bottom: -30px;" />'

            $(".goods-details .am-form ").css("display","none");
            $(".goods-details .am-u-sm-12 ").css("display","none");
            $(".goods-details .pagination-box ").css("display","none");
            $(".goods-details").append(loading);
        },
        success:function(msg){
            var tbody = $("#changeCommodity").find(".tr-box");
            var data = msg[0] ? msg[0] : [];
            console.log(data)

            tbody.empty();
            $("#pagination").empty();
            if(data.length == 0){
                var tr = "<tr><td colspan='6'>未找到相应商品</td></tr>";
                tbody.append(tr);
                return;
            }else{
                var tr = "";
                for(var i = 0; i < data.length ; i++){
                    
                    tr +='<tr><td><input type="checkbox" data-id="'+ data[i].id +'" data-stockpriceid="'+ data[i].stockpriceid +'" data-ckid="'+ data[i].ckId +'" data-has="'+ data[i].isSpecification +'" class="check-one" name=""></td>'+
                    '<td>'+ data[i].id +'</td>'+
                    '<td class="product_no">'+ data[i].product_no +'</td>'+
                    '<td class="name">'+ data[i].name +'</td>'+
                    '<td class="goodsUnit">'+ data[i].goodsUnit +'</td>'+
                    '<td class="categoryName"></td></tr>';  //缺货数量(待完成)~~~~~~~~~~~~~~~~~~~
                }
                tbody.append(tr);
            }
            //分页
            var pageOptions = {  
                AllowPaging: true,  
                PageIndex: parseInt(msg.this_page),     //设置当前页码
                PageSize: parseInt(msg.pageNum),       //设置分页大小
                RecordCount: parseInt(msg.total_num),  //设置数据总数
                // TotalPage: ,      //设置总页数
                showPageCount: 3,  
                onPageClick: function(pageIndex) {
                    
                    levelClick(category,type,pageIndex,search);
                }
            }  
            //初始化分页栏  
            $('#pagination').pageBar(pageOptions);  
        },
        complete: function () {
            $(".goods-details img").remove();
            $(".goods-details .am-form ").css("display","block");
            $(".goods-details .am-u-sm-12 ").css("display","block");
            $(".goods-details .pagination-box ").css("display","block");
        }
    });
}

// 添加审批人员
function addAudit(url,selectId,selectAudit){
    $.ajax({
        url:url,
        data:"",
        dataType:"json",
        type:"post",
        success:function(data){
            var len = data.length;
            var nickname;
            var selectBoxId = $(selectId); 
            var opation ="";
            
            if (selectAudit) {
                for(var i = 0;i < len;i ++){
                    nickname = data[i].nickname;
                    if ( nickname == selectAudit ) {
                         opation += '<option value="'+ nickname +'" selected>'+ nickname +'</option>';
                    } else {
                        opation += '<option value="'+ nickname +'">'+ nickname +'</option>';
                    }
                }
            } else {
                for(var i = 0;i < len;i ++){
                    nickname = data[i].nickname;
                    opation += '<option value="'+ nickname +'">'+ nickname +'</option>';
                }
            }
            selectBoxId.append(opation);
        }
    });
}

/** 数字金额大写转换(可以处理整数,小数,负数) */    
var digitUppercase = function(n) {  
    var fraction = ['角', '分'];  
    var digit = [  
        '零', '壹', '贰', '叁', '肆',  
        '伍', '陆', '柒', '捌', '玖'  
    ];  
    var unit = [  
        ['元', '万', '亿'],  
        ['', '拾', '佰', '仟']  
    ];  
    var head = n < 0 ? '欠' : '';  
    n = Math.abs(n);  
    var s = '';  
    for (var i = 0; i < fraction.length; i++) {  
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');  
    }  
    s = s || '整';  
    n = Math.floor(n);  
    for (var i = 0; i < unit[0].length && n > 0; i++) {  
        var p = '';  
        for (var j = 0; j < unit[1].length && n > 0; j++) {  
            p = digit[n % 10] + unit[1][j] + p;  
            n = Math.floor(n / 10);  
        }  
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;  
    }  
    return head + s.replace(/(零.)*零元/, '元')  
        .replace(/(零.)+/g, '零')  
        .replace(/^整$/, '零元整');  
}; 

function GetQueryString(name)
{
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}

function back() {
    window.history.back();
}